package com.chengyu.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengyu.core.dao.ReceiptUserOrderDao;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.CommonException;
import com.chengyu.core.mapper.OmsOrderDetailMapper;
import com.chengyu.core.model.*;
import com.chengyu.core.request.PageParamRequest;
import com.chengyu.core.response.ReceiptUserOrderDetailResponse;
import com.chengyu.core.service.ReceiptUserOrderService;
import com.chengyu.core.service.order.OrderService;
import com.chengyu.core.service.ty.TyOrderService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户发票信息 服务实现类
 * </p>
 *
 * @author macro
 * @since 2024-01-17
 */
@Service
public  class ReceiptUserOrderServiceImpl extends ServiceImpl<ReceiptUserOrderDao, ReceiptUserOrder> implements ReceiptUserOrderService {

    @Autowired
    private ReceiptUserOrderDao dao;
    @Autowired
    private OrderService orderService;

    @Autowired
    private TyOrderService tyOrderService;

    @Autowired
    private OmsOrderDetailMapper orderDetailMapper;

    /**
     * 获取列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return PageInfo
     */
    @Override
    public PageInfo<ReceiptUserOrder> getList(ReceiptUserOrder request, PageParamRequest pageParamRequest) {
        Page<ReceiptUserOrder> receiptUserOrderPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());



        LambdaQueryWrapper<ReceiptUserOrder> lqw = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(request.getUid())) {
            lqw.eq(ReceiptUserOrder::getUid,request.getUid());
        }


//        if (ObjectUtil.isNotNull(request.getMemberId())) {
//            lqw.eq(ReceiptUserOrder::getMemberId, request.getMemberId());
//        }
//
//        if (ObjectUtil.isNotNull(request.getType())) {
//            lqw.eq(ReceiptUserOrder::getType, request.getType());
//        }
//        if (StrUtil.isNotBlank(request.getTitle())) {
//            String title = URLUtil.decode(request.getTitle());
//            lqw.like(ReceiptUserOrder::getTitle, title);
//        }
//        if (StrUtil.isNotBlank(request.getAuthor())) {
//            lqw.eq(ReceiptUserOrder::getAuthor, URLUtil.decode(request.getAuthor()));
//        }
//        lqw.eq(ReceiptUserOrder::getIsDel, false);
//        lqw.orderByDesc(ReceiptUserOrder::getSort).orderByDesc(ReceiptUserOrder::getId);
        List<ReceiptUserOrder> ReceiptUserOrderList = dao.selectList(lqw);

        List<ReceiptUserOrder> responseList = new ArrayList<>();
        if (CollUtil.isEmpty(ReceiptUserOrderList)) {
            return CommonPage.copyPageInfo(receiptUserOrderPage, responseList);
        }
        for (ReceiptUserOrder ReceiptUserOrder : ReceiptUserOrderList) {
            ReceiptUserOrder response = new ReceiptUserOrder();
            BeanUtils.copyProperties(ReceiptUserOrder, response);
            responseList.add(response);
        }
        return CommonPage.copyPageInfo(receiptUserOrderPage, responseList);
    }


    @Override
    public PageInfo<ReceiptUserOrderDetailResponse> getListWidthOrder(ReceiptUserOrder request, PageParamRequest pageParamRequest) {
        Page<ReceiptUserOrderDetailResponse> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<ReceiptUserOrder> lqw = Wrappers.lambdaQuery();



        if (ObjectUtil.isNotNull(request.getUid())) {
            lqw.eq(ReceiptUserOrder::getUid,request.getUid());
        }

        List<ReceiptUserOrder> receiptUserOrderList = dao.selectList(lqw);

        List<ReceiptUserOrderDetailResponse> responseList = new ArrayList<>();
        if (CollUtil.isEmpty(receiptUserOrderList)) {
            return CommonPage.copyPageInfo(page, responseList);
        }



        List<ReceiptUserOrderDetailResponse> dataResponseList = receiptUserOrderList.stream().map(d -> {
            ReceiptUserOrderDetailResponse  dataResponse  =  new ReceiptUserOrderDetailResponse();
            BeanUtils.copyProperties(d, dataResponse);


            if(d.getOrderType().equals(1)){

                OmsOrder order = orderService.getOrderByOrderNo(d.getOrderNo());
                dataResponse.setOrder(order);


                OmsOrderDetailExample detailExample = new OmsOrderDetailExample();
                detailExample.createCriteria().andOrderIdEqualTo(order.getId());
                dataResponse.setOrderDetailList(orderDetailMapper.selectByExample(detailExample));



            }else  if(d.getOrderType().equals(2)){
                TyOrder order = tyOrderService.getOrderByOrderNo(d.getOrderNo());
                dataResponse.setTyorder(order);
            }

            return dataResponse;
        }).collect(Collectors.toList());

        return CommonPage.copyPageInfo(page, dataResponseList);
    }



    /**
     * 查询详情
     *
     * @param id Integer
     * @return ReceiptUserOrderVo
     */
    @Override
    public ReceiptUserOrder getVoByFront(Integer id)  {
        ReceiptUserOrder pmsReceiptUserOrder = getById(id);
//        if (ObjectUtil.isNull(pmsReceiptUserOrder) || pmsReceiptUserOrder.getIsDel()==1) {
//            throw new CommonException("不存在");
//        }
//        if (pmsReceiptUserOrder.getStatus()==0) {
//            throw new CommonException("不存在");
//        }
        ReceiptUserOrder ReceiptUserOrderResponse = new ReceiptUserOrder();
        BeanUtils.copyProperties(pmsReceiptUserOrder, ReceiptUserOrderResponse);
//        if (addReceiptUserOrderVisit(id)) {
//            logger.error("增加阅读次数失败，id = {}", id);
//        }
        return ReceiptUserOrderResponse;
    }

    /**
     * 获取详情
     *
     * @param id id
     * @return ReceiptUserOrder
     */
    @Override
    public ReceiptUserOrder getDetail(Integer id) {
        ReceiptUserOrder ReceiptUserOrder = getByIdException(id);
        ReceiptUserOrder response = new ReceiptUserOrder();
        BeanUtils.copyProperties(ReceiptUserOrder, response);
        return response;
    }
    @Override
    public ReceiptUserOrderDetailResponse getDetailWidthOrder(Integer id) {
        ReceiptUserOrder ReceiptUserOrder = getByIdException(id);

        ReceiptUserOrderDetailResponse receiptUserOrderDetailResponse = new ReceiptUserOrderDetailResponse();
        BeanUtils.copyProperties(ReceiptUserOrder, receiptUserOrderDetailResponse);

        OmsOrder order = orderService.getOrderByOrderNo(ReceiptUserOrder.getOrderNo());
        receiptUserOrderDetailResponse.setOrder(order);
        return receiptUserOrderDetailResponse;
    }






    /**
     * 增加浏览次数
     *
     * @param id id
     * @return
     */
    public boolean addReceiptUserOrderVisit(Integer id) {
        UpdateWrapper<ReceiptUserOrder> wrapper = Wrappers.update();
        wrapper.setSql("visit = visit + 1");
        wrapper.eq("id", id);
        return update(wrapper);
    }


    /**
     * 获取移动端热门列表
     *
     * @return List<ReceiptUserOrder>
     */
    @Override
    public List<ReceiptUserOrder> getHotList() {
        LambdaQueryWrapper<ReceiptUserOrder> lqw = Wrappers.lambdaQuery();
//        lqw.select(ReceiptUserOrder::getId, ReceiptUserOrder::getCover, ReceiptUserOrder::getTitle, ReceiptUserOrder::getCreateTime);
//        lqw.eq(ReceiptUserOrder::getIsHot, true);
//        lqw.eq(ReceiptUserOrder::getStatus, true);
//        lqw.eq(ReceiptUserOrder::getIsDel, false);
//        lqw.orderByDesc(ReceiptUserOrder::getSort, ReceiptUserOrder::getId);
        lqw.last(" limit 20");
        List<ReceiptUserOrder> ReceiptUserOrderList = dao.selectList(lqw);
        if (CollUtil.isEmpty(ReceiptUserOrderList)) {
            return CollUtil.newArrayList();
        }
        return ReceiptUserOrderList.stream().map(e -> {
            ReceiptUserOrder ReceiptUserOrderResponse = new ReceiptUserOrder();
            BeanUtils.copyProperties(e, ReceiptUserOrderResponse);
            return ReceiptUserOrderResponse;
        }).collect(Collectors.toList());
    }

    /**
     * 新增
     *
     * @param request 新增参数
     * @return Boolean
     */
    @Override
    public Boolean create(ReceiptUserOrder request) {
        ReceiptUserOrder ReceiptUserOrder = new ReceiptUserOrder();
        BeanUtils.copyProperties(request, ReceiptUserOrder);
//        ReceiptUserOrder.setId(null);
////        String cdnUrl = systemAttachmentService.getCdnUrl();
////        ReceiptUserOrder.setCover(systemAttachmentService.clearPrefix(ReceiptUserOrder.getCover(), cdnUrl));
////        ReceiptUserOrder.setContent(systemAttachmentService.clearPrefix(ReceiptUserOrder.getContent(), cdnUrl));
//        ReceiptUserOrder.setVisit(0L);
        return save(ReceiptUserOrder);
    }


    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean updateReceiptUserOrder(ReceiptUserOrder request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new CommonException("ID不能为空");
        }
        ReceiptUserOrder  ReceiptUserOrder  =  getByIdException(request.getId());
//        if(ReceiptUserOrder.getMemberId().equals(request.getMemberId())){

//        ReceiptUserOrder ReceiptUserOrder = new ReceiptUserOrder();
        BeanUtils.copyProperties(request, ReceiptUserOrder);
//        String cdnUrl = systemAttachmentService.getCdnUrl();
//        ReceiptUserOrder.setCover(systemAttachmentService.clearPrefix(ReceiptUserOrder.getCover(), cdnUrl));
//        ReceiptUserOrder.setContent(systemAttachmentService.clearPrefix(ReceiptUserOrder.getContent(), cdnUrl));
        return updateById(ReceiptUserOrder);
//        }else{
//            throw new CommonException("操作错误");
//        }
    }




    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean pushReceiptUserOrder(ReceiptUserOrder request) {
//        if (ObjectUtil.isNull(request.getId())) {
//            throw new CommonException("ID不能为空");
//        }
//        getByIdException(request.getId());
//        ReceiptUserOrder ReceiptUserOrder = new ReceiptUserOrder();
//        BeanUtils.copyProperties(request, ReceiptUserOrder);


//        String[] imagesdList = request.getImages().split(CommonConstant.DH_REGEX);
//
//        if(imagesdList!=null) request.setCover(imagesdList[0]);

        if(request.getId() == null){
            return  create(request);
        }else{
            return updateReceiptUserOrder(request);
        }


    }



    /**
     * 删除
     *
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean deleteById(Integer id) {
        ReceiptUserOrder ReceiptUserOrder = getByIdException(id);
        ReceiptUserOrder.setStatus(-1);
        return updateById(ReceiptUserOrder);
    }


    @Override
    public Boolean deleteByIdWithMemberId(Integer id,Integer memberId) {
        ReceiptUserOrder receiptUserOrder = getByIdMemberIdException(id,memberId);

        System.out.println(id);
        System.out.println(memberId);


        if (memberId.equals(0) ) {
            throw new CommonException("操作错误1！！！！！！");
        }

        if (!memberId.equals(receiptUserOrder.getUid())) {
            throw new CommonException("操作错误2！！！！！！");
        }



        receiptUserOrder.setStatus(-1);
        return updateById(receiptUserOrder);
    }

    private ReceiptUserOrder getByIdException(Integer id) {
        ReceiptUserOrder ReceiptUserOrder = getById(id);
        if (ObjectUtil.isNull(ReceiptUserOrder) || ReceiptUserOrder.getStatus()==-1) {
            throw new CommonException("不存在");
        }
        return ReceiptUserOrder;
    }

    private ReceiptUserOrder getByIdMemberIdException(Integer id,Integer memberId) {
        ReceiptUserOrder ReceiptUserOrder = getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("uid", memberId);
        List<ReceiptUserOrder> list = dao.selectByMap(map);

        list.forEach(System.out::println);



        if (ObjectUtil.isNull(ReceiptUserOrder) || ReceiptUserOrder.getStatus()==-1) {
            throw new CommonException("不存在");
        }
        return ReceiptUserOrder;
    }



    /**
     * 是否使用分类
     *
     * @param categoryId 分类ID
     * @return Boolean
     */
    @Override
    public Boolean isUseCategory(Integer categoryId) {
        LambdaQueryWrapper<ReceiptUserOrder> lqw = Wrappers.lambdaQuery();
//        lqw.eq(ReceiptUserOrder::getType, categoryId);
        lqw.eq(ReceiptUserOrder::getIsDel, false);
        lqw.eq(ReceiptUserOrder::getIsDel, false);
        lqw.last(" limit 1");
        ReceiptUserOrder ReceiptUserOrder = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(ReceiptUserOrder);
    }


//        if (Yii::$app->tinyShopService->orderInvoice->findByOrderId($model->order_id)) {
//        return ResultHelper::json(422, '已申请发票，不可重新补发票');
//    }
//
//    // 发票记录
//        if (!empty($previewForm->invoice)) {
//        Yii::$app->tinyShopService->orderInvoice->create($order, $previewForm->invoice, $previewForm->invoice_content);
//    }


    /**
     * 开关
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean ReceiptUserOrderSwitch(Integer id) {
        ReceiptUserOrder ReceiptUserOrder = getByIdException(id);
        ReceiptUserOrder.setStatus(ReceiptUserOrder.getStatus()==-1?0:-1);
        return updateById(ReceiptUserOrder);
    }
}
